<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :title="getTitle"
    :width="adaptiveWidth"
    @ok="handleSubmit"
    :showFooter="showFooter"
    destroyOnClose
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, ref, unref, useAttrs} from 'vue';
import {BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from './user.data';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {saveOrUpdateUser, queryBusinessIdByUserId, queryBusinessByIds} from './user.api';
import {useDrawerAdaptiveWidth} from '/@/hooks/jeecg/useAdaptiveWidth';
import { dateUtil } from "/@/utils/dateUtil";
// 声明Emits
  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs();
  const isUpdate = ref(true);
  const rowId = ref('');
  const businessOptions = ref([]);

  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  // TODO [VUEN-527] https://www.teambition.com/task/6239beb894b358003fe93626
  const showFooter = ref(true);
  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    showFooter.value = data?.showFooter ?? true;
    setDrawerProps({ confirmLoading: false, showFooter: showFooter.value });
    isUpdate.value = !!data?.isUpdate;
    businessOptions.value = [];//初始化
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      data.record.middleOptAuth = data.record.middleOptAuth.toString();//角色选择数字转字符串
      //根据中台用户ID查询绑定的商户id
      let businessId = await queryBusinessIdByUserId({userId: data.record.id});
      if(businessId.length > 0){
        data.record.businessIds = businessId.join(',');
      }
      //处理绑定公司数据
      let businessList = await queryBusinessByIds({businessIds: data.record.businessIds});
      if(businessList.length > 0){
        businessList.forEach((item) => {
          businessOptions.value.push({value: item.id, text: item.name});
        });
      }
    }
    let isRole = true;
    if(data.record?.middleOptAuth==='0'){
      isRole = false;
    }
    //编辑时隐藏密码/角色列表隐藏角色信息/我的部门时隐藏所属部门
    updateSchema([
      {
        field: 'password',
        show: !unref(isUpdate),
      },
      {
        field: 'confirmPassword',
        ifShow: !unref(isUpdate),
      },
      {
        field: 'middleOptAuth',
        ifShow: unref(isRole),
      },
      {
        field: 'businessIds',
        ifShow: unref(isUpdate) && data.record?.middleOptAuth==='2',
        componentProps: {
          options: businessOptions.value,
        },
      },
    ]);
    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === 'object') {
      setFieldsValue({
        ...data.record,
      });
    }
    // 隐藏底部时禁用整个表单
    //update-begin-author:taoyan date:2022-5-24 for: VUEN-1117【issue】0523周开源问题
    setProps({ disabled: !showFooter.value });
    //update-end-author:taoyan date:2022-5-24 for: VUEN-1117【issue】0523周开源问题
  });
  //获取标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增用户' : (showFooter.value) ? '编辑用户' : '详情'));
  const { adaptiveWidth } = useDrawerAdaptiveWidth();

  //提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({ confirmLoading: true });
      values.userIdentity === 1 && (values.departIds = '');
      let isUpdateVal = unref(isUpdate);
      //提交表单
      await saveOrUpdateUser(values, isUpdateVal);
      //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success',{isUpdateVal ,values});
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
